import {getMenus, logout, modifyPassword} from '../services/common/common';
import {queryMenusTreeJSON} from '../services/auth/menu';
import {getBusinessParamsByCode} from '../services/basedata/businessParams';
import {getAllCurrencys} from '../services/basedata/currency';
import {getAllPorts} from '../services/basedata/placeclearance';
import {getAreaTree} from '../services/basedata/area';
import {getRecAccListOfCstid} from '../services/customer/RecAcc';
import {getIndustryTree} from '../services/basedata/industry'
import {getManagerList, getUserInfo, updateUser, register} from '../services/auth/user';
import {browserHistory} from 'dva/router';

const R = require('ramda');
import {message} from "antd";
import Constants from '../utils/Constants';
import {queryAllRoleList} from "../services/auth/role";
import {queryLesseeOrganizations} from "../services/auth/organization";
import {getLessee, queryAllLessees, queryLessees} from "../services/auth/lessee";

let portsLoading = 0;
let currencysCstId = {};

/**
 * 删除叶子节点children属性
 *
 * @param item
 */
function removeLeafChildren(item) {
  item.key = item.orgId;
  if (item.children.length === 0) {
    delete item.children;
  } else {
    item.children.map(temp => {
      removeLeafChildren(temp);
    });
  }
}

export default {
  namespace: 'app',
  state: {
    dataSource: {},
    layoutMode: 'blank', // 模式：blank、navigate
    isDisplayBreadcrumb: true, // 是否显示面包屑导航
    menus: [], // 菜单
    menuSelect: [], // 菜单选中
    bizParams: {}, // 业务参数缓存
    currencys: [], // 币种列表
    ports: [], //报关口岸列表
    areaTree: [], //省市级联树
    industryTree: [], //行业级联树
    showResetPassword: false, //是否显示重置密码的窗口
    recAcc: [],
    manager: {},
    lesseelist: [],
    editModel: { // 编辑视图
      showStatus: false, // 默认不显示
      confirmLoading: false, // 确认按钮loading状态
      title: '创建用户', // 标题
      type: 'add', // 编辑类型：add-创建，update-修改
      form: {
        userId: 0,
        userName: '',
        loginPwd: '',
        loginId: '',
        mobile: '',
        email: '',
        orgIds: '',
        roleIds: []
      }
    }
  },
  reducers: {

    /**
     * 刷新state
     *
     * @param state
     */
    refreshState(state, {payload}) {
      return {...state, ...payload};
    },


    /**
     * 设置布局模式
     *
     * @param state
     * @param action
     * @returns {{layoutMode: (*|string)}}
     */
    setLayoutMode(state, action) {
      return {...state, layoutMode: action.layoutMode}
    },
    /**
     * 设置是否显示面包屑导航
     *
     * @param state
     * @param action
     * @returns {{isDisplayBreadcrumb: (*|boolean)}}
     */
    setIsDisplayBreadcrumb(state, action) {
      return {...state, isDisplayBreadcrumb: action.isDisplayBreadcrumb}
    },
    /**
     * 设置菜单
     *
     * @param state
     * @param action
     * @returns {{menus: (Array|*)}}
     */
    setMenus(state, action) {
      return {...state, menus: action.menus};
    },
    /**
     * 菜单选中
     *
     * @param state
     * @param action
     * @returns {{menuSelect: (Array|*)}}
     */
    setMenuSelect(state, action) {
      return {...state, menuSelect: action.menuSelect};
    },
    /**
     * 设置业务参数
     *
     * @param state
     * @param payload
     */
    setBizParams(state, {payload}) {
      let newState = state.bizParams;
      if (payload.sprCode != undefined) {
        newState[payload.sprCode] = payload.list;
      }
      return {...state, bizParams: newState};
    },
    /**
     * 设置币种列表
     *
     * @param state
     * @param payload
     */
    setCurrencys(state, {payload}) {
      return {...state, currencys: payload.currencys};
    },
    /**
     * 设置口岸列表
     *
     * @param state
     * @param payload
     */
    setPorts(state, {payload}) {
      return {...state, ports: payload.ports};
    },
    /**
     * 设置省市级联树
     *
     * @param state
     * @param payload
     */
    setAreaTree(state, {payload}) {
      return {...state, areaTree: payload.areaTree};
    },
    /**
     * 设置行业级联数
     * @param state
     * @param payload
     */

    setIndustryTree(state, {payload}) {
      return {...state, industryTree: payload.industryTree};
    },
    /**

     /**
     * 设置是否显示修改密码
     *
     * @param state
     * @param payload
     */
    setShowResetPassword(state, {payload}) {
      return {...state, showResetPassword: payload.showResetPassword};
    },

    /**
     * 设置收款账户
     * @param state
     * @param payload
     * @returns {{recAcc: string}}
     */
    setRecAcc(state, {payload}) {
      let newState = state.recAcc;

      if (payload.cstId != undefined) {
        newState[payload.cstId] = payload.ports;
      }
      return {...state, recAcc: newState};
    },

    /**
     * 设置管理人员
     * @param state
     * @param action
     * @returns {{dataSource: (state.customer|{}|*|payload.customer|string), attachments: (state.attachments|{}|*)}}
     */
    setManager(state, action) {
      let payload = action.payload;
      return {...state, manager: payload.manager};
    },
    /**
     * 是否显示用户信息
     *
     * @param state
     * @param action
     * @returns {{showStatus: (boolean|*)}}
     */
    setEditModel(state, action) {
      let payload = action.payload;
      let newState = {...state.editModel};
      if (payload.showStatus != undefined) {
        newState.showStatus = payload.showStatus;
      }
      if (payload.title != undefined) {
        newState.title = payload.title;
      }
      if (payload.confirmLoading != undefined) {
        newState.confirmLoading = payload.confirmLoading;
      }
      if (payload.type != undefined) {
        newState.type = payload.type;
      }
      if (payload.form != undefined) {
        newState.form = payload.form;
      }
      return {...state, editModel: {...newState}};
    },
    /**
     * 设置所有角色数据列表
     *
     * @param state
     * @param action
     */
    setAllRoleList(state, {payload}) {
      return {...state, allRoles: payload.allRoles}
    },
    /**
     * 设置组织数据列表
     *
     * @param state
     * @param action
     */
    setList(state, {payload}) {
      return {...state, list: payload.list}
    },
    /**
     * 设置租户数据列表
     *
     * @param state
     * @param action
     */
    setLesseeList(state, {payload}) {
      return {...state, lesseelist: payload.list, page: payload.page}
    },

  },
  effects: {

    * getLessee({payload, callback}, {call, put, select}) {
      if (sessionStorage.ACJSESSIONID) {
        const res = yield call(getLessee, {lesseeId: payload.lesseeId});
        if (res.data.resultCode === "ok") {
          let content = res.data.content;
          let lessee = content.data.lessee;
          if (callback) {
            callback(lessee)
          }
          yield put({
            type: 'refreshState',
            payload: {
              dataSource: lessee
            }
          });
        } else {
          message.error(res.data.errMessage);
        }
      }

    },


    /**
     * 修改用户
     *
     * @param payload
     * @param call
     * @param put
     * @param select
     */* updateUser({payload}, {call, put, select}) {
      const res = yield call(updateUser, {
        userId: payload.userId,
        username: payload.username,
        loginId: payload.loginId,
        mobile: payload.mobile,
        email: payload.email,
        orgIds: payload.orgIds,
        roleIds: payload.roleIds
      });
      if (res.data.resultCode === "ok") {
        message.info("修改成功！");
        yield put({
          type: 'setEditModel',
          payload: {
            showStatus: false
          }
        });
      }
    },
    /**
     * 查询租户集合
     *
     * @param call
     * @param put
     * @param select
     */* queryLessees({}, {call, put, select}) {
      const search = yield select(state => state.lessee.search);
      const page = yield select(state => state.lessee.page);

      const res = yield call(queryLessees, {
        lesseeCode: search.lesseeCode,
        lesseeName: search.lesseeName,
        status: search.status,
        page
      });
      if (res.data.resultCode === "ok") {
        let content = res.data.content;
        yield put({
          type: 'setLesseeList',
          payload: {
            list: content.list,
            page: content.page
          }
        });
      }
    },
    * queryAllLessees({}, {call, put, select}) {
      const res = yield call(queryAllLessees, {});
      if (res.data.resultCode === "ok") {
        let content = res.data.content;
        yield put({
          type: "setLesseeList",
          payload: {
            list: content.data,
          }
        })
      }
    },
    /**
     * 查询组织架构
     *
     * @param call
     * @param put
     * @param select
     */* queryOrganizations({}, {call, put, select}) {
      const res = yield call(queryLesseeOrganizations);
      if (res.data.resultCode === "ok") {
        let list = res.data.content;

        list = list.map(item => {
          removeLeafChildren(item);
          return item;
        });

        yield put({
          type: 'setList',
          payload: {
            list: list
          }
        });
      }
    },
    /**
     * 获取当前登录用户菜单集合
     *
     * @param appCode
     * @param pathname
     * @param call
     * @param put
     * @param select
     */* getMenus({pathname,callback}, {call, put, select}) {
      const res = yield call(getMenus);
      if (res.data.resultCode === 'ok') {
        let menus = res.data.content;
        let menuSelect = [];
        if(callback){callback(menus)}
        menus.map(menu => {
          if (pathname.includes(menu.url)) {
            menuSelect.push(menu.menuId + "");
          }
        });
        yield put({type: 'setMenuSelect', menuSelect: menuSelect});
        yield put({type: 'setMenus', menus: menus});
      }
    },
    /**
     * 退出登录
     *
     * @param call
     * @param put
     */* logout({}, {call, put}) {
      yield call(logout);
      sessionStorage.clear();
      browserHistory.push("/login");
    },
    /**
     * 获取业务参数集合
     *
     * @param call
     * @param put
     * @param select
     */* getBusinessParamsByCode({sprCode}, {call, put, select}) {
      const sessionSprCode = sessionStorage.getItem(Constants.PARAMPREFIX + sprCode);
      if (R.isNil(sessionSprCode)) {
        const res = yield call(getBusinessParamsByCode, {sprCode});
        if (res.data.resultCode === 'ok') {
          sessionStorage.setItem(Constants.PARAMPREFIX + sprCode, JSON.stringify(res.data.content));
          yield put({type: 'setBizParams', payload: {sprCode, list: res.data.content}});
        }
      } else {
        yield put({type: 'setBizParams', payload: {sprCode, list: JSON.parse(sessionSprCode)}});
      }

    },
    /**
     * 获取所有币种
     *
     * @param call
     * @param put
     */* getAllCurrencys({}, {call, put, select}) {
      const sessionCurrency = sessionStorage.getItem(Constants.preCurrency);
      if (R.isNil(sessionCurrency)) {
        const res = yield call(getAllCurrencys);
        if (res.data.resultCode === 'ok') {
          sessionStorage.setItem(Constants.preCurrency, JSON.stringify(res.data.content));
          yield put({type: 'setCurrencys', payload: {currencys: res.data.content}});
        }
      } else {
        yield put({type: 'setCurrencys', payload: {currencys: JSON.parse(sessionCurrency)}});
      }
    },
    /**
     * 获取所有口岸
     *
     * @param call
     * @param put
     */* getAllPorts({}, {call, put, select}) {
      const sessionPort = sessionStorage.getItem(Constants.PORTS);
      if (R.isNil(sessionPort)) {
        const res = yield call(getAllPorts, {status: "1"});
        if (res.data.resultCode === 'ok') {
          sessionStorage.setItem(Constants.PORTS, JSON.stringify(res.data.content));
          let data = res.data.content;
          yield put({
            type: 'setPorts',
            payload: {
              ports: data
            }
          });
        }
      } else {
        yield put({type: 'setPorts', payload: {ports: JSON.parse(sessionPort)}});
      }
    },
    /**
     * 获取所有口岸
     *
     * @param call
     * @param put
     */* getAreaTree({}, {call, put, select}) {
      const areaTreeSession = sessionStorage.getItem("areaTree");
      if (R.isNil(areaTreeSession)) {
        const res = yield call(getAreaTree,);
        if (res.data.resultCode === 'ok') {
          let data = res.data.content;
          sessionStorage.setItem("areaTree", JSON.stringify(data));//sessionStorage只能存字符串
          yield put({
            type: 'setAreaTree',
            payload: {
              areaTree: data
            }
          });
        }
      } else {
        yield put({
          type: 'setAreaTree',
          payload: {
            areaTree: JSON.parse(areaTreeSession)
          }
        });
      }
    },

    /**
     * 获取主营行业
     * @param call
     * @param put
     * @param select
     */* getIndustryTree({}, {call, put, select}) {
      const industryTreeSession = sessionStorage.getItem("industryTree");
      if (R.isNil(industryTreeSession)) {
        const res = yield call(getIndustryTree);
        if (res.data.resultCode === 'ok') {
          let data = res.data.content;
          sessionStorage.setItem("industryTree", JSON.stringify(data));//sessionStorage只能存字符串
          yield put({
            type: 'setIndustryTree',
            payload: {
              industryTree: data
            }
          });
        }
      } else {
        yield put({
          type: 'setIndustryTree',
          payload: {
            industryTree: JSON.parse(industryTreeSession)
          }
        });
      }
    },


    /**
     * 修改密码
     *
     * @param call
     * @param put
     */* modifyPassword({payload}, {call, put, select}) {
      const res = yield call(modifyPassword, {oldPwd: payload.oldPassword, newPwd: payload.loginPwd});
      if (res.data.resultCode === 'ok') {
        message.info("密码修改成功，下次登录登陆生效");
        if (payload.onSuccess) {
          payload.onSuccess()
        }
      } else {
        message.error(res.data.errMessage);
        if (payload.onFail) payload.onFail();
      }
    },

    /**
     * 获取收款人账户
     * @param cstId
     * @param call
     * @param put
     * @param select
     */* getRecAccListOfCstid({cstId}, {call, put, select}) {
      const res = yield call(getRecAccListOfCstid, {cstId});
      if (res.data.resultCode === 'ok') {
        let data = res.data.content;
        currencysCstId[cstId] = true;
        yield put({
          type: 'setRecAcc',
          payload: {
            cstId,
            ports: data
          }
        });
      }
    },

    /**
     * 获取管理人员
     * @param payload
     * @param call
     * @param select
     * @param put
     */* getManagerList({payload}, {call, select, put}) {
      const res = yield call(getManagerList, {});
      if (res.data.resultCode === "ok") {
        let data = res.data.content;
        yield put({
          type: "setManager",
          payload: {
            manager: data,
          }
        });
      }
    },
    /**
     * 查询所有角色集合
     *
     * @param call
     * @param put
     * @param select
     */* queryAllRoleList({}, {call, put, select}) {
      const res = yield call(queryAllRoleList);
      if (res.data.resultCode === "ok") {
        let content = res.data.content;
        yield put({
          type: 'setAllRoleList',
          payload: {
            allRoles: R.isNil(content) ? [] : content,
          }
        });
      }
    },

    * registeruser({payload}, {call, select, put}) {
      yield put({
        type: "setEditModel",
        payload: payload
      })
    },

    /***
     * 获取当前用户
     * @param payload
     * @param call
     * @param select
     * @param put
     */* getUserInfo({payload}, {call, select, put}) {
      const res = yield call(getUserInfo, {});
      const organization = yield call(queryLesseeOrganizations);
      const roles = yield call(queryAllRoleList);
      if (res.data.resultCode == "ok" && organization.data.resultCode == "ok" && roles.data.resultCode == "ok") {
        let content = res.data.content;
        let rolesContent = roles.data.content;
        let orgContent = organization.data.content;
        orgContent = orgContent.map(item => {
          removeLeafChildren(item);
          return item;
        });

        let roleIds = [];
        if (!R.isNil(content.roles)) content.roles.map((item) => roleIds.push(item.roleId + ""));
        yield put({
          type: 'setEditModel',
          payload: {
            showStatus: true,
            confirmLoading: false,
            title: '用户信息',
            type: 'update',
            form: {
              userId: content.userId,
              username: content.username,
              loginPwd: content.loginPwd,
              loginId: content.loginId,
              mobile: content.mobile,
              email: content.email,
              orgIds: content.orgIds,
              roleIds: roleIds,
              roles: R.isNil(rolesContent) ? [] : rolesContent,
              organization: R.isNil(orgContent) ? [] : orgContent,
            }
          }
        })
      }
    },

    /**
     * 注册
     * */* register({payload}, {call, select, put}) {
      const res = yield call(register, {
        username: payload.username,
        loginId: payload.loginId,
        mobile: payload.mobile,
        email: payload.email,
        lesseeCode: payload.lessee,
        loginPwd: payload.loginPwd,
      });
      if (res.data.resultCode == "ok") {
        if (payload.onSuccess) payload.onSuccess();
      }
    }


  },



  subscriptions: {
    setup({history, dispatch}) {
      return history.listen(({pathname}) => {

        // if (sessionStorage.ACJSESSIONID && !sessionStorage.lesseeNameCn) {
        //   dispatch({
        //     type: 'app/getLessee',
        //     payload: {
        //       lesseeId: 1
        //     },
        //     callback(res) {
        //       sessionStorage.lesseeNameCn = res.lesseeNameCn
        //     }
        //   })
        // }

        if (pathname.includes('/logout')) {
          dispatch({type: 'logout'});
          sessionStorage.clear();
        } else {
          if (pathname.includes('/index')) {
            dispatch({type: 'setIsDisplayBreadcrumb', isDisplayBreadcrumb: false});
          } else {
            dispatch({type: 'setIsDisplayBreadcrumb', isDisplayBreadcrumb: true});
          }
          // if (!pathname.includes('login')) {
          if(!pathname.includes('login')&&!sessionStorage.menuTree){
            dispatch({
              type: 'getMenus', pathname, callback(res) {
                sessionStorage.menuTree = JSON.stringify(res)
              }
            });
          }
        }
      });


    }
  }
};


// WEBPACK FOOTER //
// ./public/src/models
